package com.why.blog.controller.admin;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.why.blog.bean.Blog;
import com.why.blog.bean.Type;
import com.why.blog.bean.resultType;
import com.why.blog.service.BlogService;
import com.why.blog.service.typeService;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @program: blog
 * @description:
 * @author: @why
 * @create: 2021-01-20 20:56
 **/
@Slf4j
@Controller
@RequestMapping("/admin")
public class editCotroller {

    @Autowired
    private BlogService blog;

    @Autowired
    private typeService type;

    //上传文件的位置   C://Users//yasuo//Desktop//Book
    @Value("${file.uploadFolder}")
    private String realBasePath;
    //文件访问的位置
    @Value("${file.accessPath}")
    private String accessPath;

    /**
     * If  it is not default by blog id,  and start to update otherwise start to add blog.
     *
     * @param blogId
     * @return
     */

    @GetMapping("/edit")
    public String editBlog(@RequestParam(name = "id", defaultValue = "-1") Integer blogId, Model model) {
        if (blogId != -1) {
            Blog blogById = blog.getBlogById(blogId);
            model.addAttribute("blog", blogById);
            // log.warn(blogById.toString());

        } else {
            //To add a object of empty that stop thymealf to warn.
            model.addAttribute("blog", new Blog());
           


        }
        //分类的内容
        List<Type> type = this.type.getListType();
        model.addAttribute("types", type);

        return "admin/edit";
    }

    /**
     * To save blog message.
     *
     * @param blog
     * @return
     * @requestBody注解常用来处理 content-type不是默认的application/x-www-form-urlcoded编码的内容，
     * 比如说：application/json或者是application/xml等。
     * 一般情况下来说常用其来处理application/json类型。
     */
    @RequestMapping("/addBlog")
    public String addBlog(Blog blog, HttpServletRequest request, RedirectAttributes attributes) {
        //如果没有添加分类的时候，不接收此请求，返回到edit页面
        String categoryId = request.getParameter("categoryId");
        String blogId = request.getParameter("blogId");
        if (!StringUtils.hasLength(categoryId)) {
            attributes.addFlashAttribute("msg","请选择分类！");
            if (StringUtils.hasLength(blogId)) {
                return "redirect:/admin/edit?id="+blogId;
            }else {
                return "redirect:/admin/edit";
            }
        }
        //得到博客id，判断是修改还是新增

        blog.setType(new Type(Integer.valueOf(categoryId), null, null));
        //有id，是更新
        if (StringUtils.hasLength(blogId)) {
            blog.setId(Integer.valueOf(blogId));
            this.blog.updateBlog(blog);
        } else {
            blog.setViews(0);
            this.blog.saveBlog(blog);
        }
        attributes.addFlashAttribute("msg","添加或修改博客，成功！");

        return "redirect:/admin/edit";
    }


    /**
     * 图片上传
     *
     * @param file
     * @param request
     * @param response
     * @return
     */

    @RequestMapping("/upload")
    @ResponseBody
    public String editormdPic(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        try {

            // 获取图片后缀名字
            String imgSuffix = file.getOriginalFilename();
            log.error("源文件名字imgSuffix is --" + imgSuffix);
            // 文件唯一的名字，先获取文件类型的后缀名，再使用时间戳生成标示唯一文件名
            String fileName = System.currentTimeMillis() + "." + imgSuffix.split("\\.")[1];
            //一个月生成一个新文件夹
            Date todayDate = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
            String today = dateFormat.format(todayDate);


            // 域名访问的相对路径（通过浏览器访问的链接-虚拟路径）
            String saveToPath = accessPath + today + "/";

            // 真实路径，实际储存的路径
            String realPath = realBasePath + today + "/";
            // 储存文件的物理路径，使用本地路径储存
            String filepath = realPath + fileName;
           //log.error(filepath);
           // log.error("上传图片名为：" + fileName + "--虚拟文件路径为：" + saveToPath + "--物理文件路径为：" + realPath);
            // 指定文件路径是realPath，文件名是fileName
            File destFile = new File(realPath, fileName);
            //判断是否有该文件夹存在
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            //文件保存到指定物理路径
            file.transferTo(destFile);
            //将响应结果传递到客户端
            ObjectMapper objectMapper = new ObjectMapper();
            resultType type = new resultType(saveToPath + fileName, "upload success！", 1);
            String value = objectMapper.writeValueAsString(type);

            return value;
        } catch (Exception e) {
            //当上传失败，返回客户端失败的结果
            return "{message: \"upload failure!\", success: 0}";
        }


    }


    @RequestMapping("/test")
    @ResponseBody
    public String test(HttpServletRequest request) {
        return request.getSession().getServletContext().getRealPath("/");
    }


}

